const express = require('express')
const xlsx = require('xlsx')
const { sendResponse } = require('../utils/sendResponse.js')
const { getFilePath } = require('../utils/constants.js') // 引入常量

const router = express.Router()

// 使用绝对路径
const commentsFilePath = getFilePath('comments')
const usersFilePath = getFilePath('users') // 用户文件路径

// 获取文章的评论路由
router.get('/getComments', (req, res) => {
  const articleId = req.query.articleId

  // 读取评论 Excel 文件中的数据
  const commentsWorkbook = xlsx.readFile(commentsFilePath)
  const commentsWorksheet = commentsWorkbook.Sheets['comments']
  const commentsData = xlsx.utils.sheet_to_json(commentsWorksheet)

  // 读取用户 Excel 文件中的数据
  const usersWorkbook = xlsx.readFile(usersFilePath)
  const usersWorksheet = usersWorkbook.Sheets['users']
  const usersData = xlsx.utils.sheet_to_json(usersWorksheet)

  // 根据 articleId 筛选出相关的评论
  const articleComments = commentsData.filter((comment) => comment.ArticleID === articleId)

  // 如果没有找到相关评论
  if (articleComments.length === 0) {
    return sendResponse(res, 200, {}, '没有找到相关评论。')
  }

  // 为每条评论添加用户信息
  const commentsWithUserInfo = articleComments.map((comment) => {
    const user = usersData.find((user) => user.ID === comment.AuthorID) || {}
    return {
      ...comment,
      authorInfo: {
        id: user.ID,
        nickname: user.Nickname,
        gender: user.Gender,
        phone: user.Phone,
        account: user.Account,
        followers: user.Followers,
        totalWordsWritten: user.TotalWordsWritten,
        totalLikes: user.TotalLikes,
        avatar: user.Avatar
      },
      children: [] // 初始化 children 数组
    }
  })

  // 构建评论树结构：
  // 1. 顶级评论是针对文章的评论，ParentCommentID 为 null
  // 2. 子评论是针对评论的回复，ParentCommentID 不为 null
  const topLevelComments = commentsWithUserInfo.filter((comment) => !comment.ParentCommentID)
  const childComments = commentsWithUserInfo.filter((comment) => comment.ParentCommentID)

  // 将子评论归类到相应的父评论中
  topLevelComments.forEach((parentComment) => {
    parentComment.children = childComments.filter((child) => child.ParentCommentID === parentComment.ID).sort((b, a) => new Date(b.CreatedAt) - new Date(a.CreatedAt)) // 子评论按时间倒序排列
  })

  // 顶层评论按时间倒序排列
  const sortedComments = topLevelComments.sort((a, b) => new Date(b.CreatedAt) - new Date(a.CreatedAt))

  // 返回带有用户信息并且按时间排序的评论数据
  return sendResponse(res, 200, sortedComments, '评论获取成功！')
})

module.exports = router
